<?php

class CleancommentsCommand extends CConsoleCommand
{

	public function getCommentTargets(){
		$cmd = Yii::app()->db->createCommand('select distinct target_type from '.Comment::model()->tableName());
		$types = $cmd->queryColumn();
		foreach($types as $i => $type){
			if(!Comment::model()->getMetaData()->hasRelation($type)){
				unset($types[$i]);
			}
		}
		return $types;
	}
	
	/**
	 * 
	 * @param Comment[] $cs
	 */
	public function cleanScope($cs){
		foreach($cs as $c){
			if($chs = $c->comments){
				$this->cleanScope($chs);
			}
			echo (int)$c->delete();
		}
	}
	
	/**
	 * @param string $type
	 */
	public function cleanByTarget($type) {
		$targetModelName = ucfirst($type);
		$targetModel = call_user_func(array($targetModelName,'model'));
		$targetPk = $targetModel->getTableSchema()->primaryKey;
		$cs = Comment::model()->findAll(array(
			'with' => array($type => array('alias' => 'commentTarget')),
			'condition' => '{%this}.target_type="'.$type.'" '
				.'and commentTarget.'.$targetPk.' is null '
				.'and {%this}.comment_pid is null',
		));
		
		$this->cleanScope($cs);
		
	}
	
	/**
	 * Execute the action.
	 * @param array command line parameters specific for this command
	 */
	public function run($args)
	{
		$types = $this->commentTargets;
		foreach ($types as $type){
			echo "cleaning '$type'...\r\n";
			$this->cleanByTarget($type);
			echo "\r\n";
		}
		
		if(@$args[0] == 'end'){
			exit;
		}
		
	}

}